<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="等级名称">
          <el-input
            v-model="queryParams.memberLevelName"
            placeholder="请输入等级名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd" v-hasPerm="['genealogy:member-level:add']">
            <template #icon><Plus /></template>
            新增
          </el-button>
        </el-form-item>
        <el-form-item label="关联角色" style="margin-left: 20px">
          <el-select
            v-model="selectedRoleId"
            placeholder="请选择角色筛选"
            clearable
            style="width: 200px"
            @change="handleRoleFilter"
          >
            <el-option
              v-for="role in roleList"
              :key="role.code"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="filteredPageData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="id" label="ID" prop="id" min-width="80" align="center" />
        <el-table-column key="levelName" label="等级名称" prop="levelName" min-width="120" align="center" />
        <el-table-column key="roleId" label="关联角色" min-width="120" align="center">
          <template #default="scope">
            {{ roleList.find(role => role.id === scope.row.roleId)?.name || '-' }}
          </template>
        </el-table-column>
        <el-table-column key="sort" label="等级" prop="sort" min-width="80" align="center" />
        <el-table-column key="sort1" label="子等级" prop="sort1" min-width="80" align="center" />
        <!-- <el-table-column key="personLimit" label="人数限制" prop="personLimit" min-width="100" align="center" /> -->
        <el-table-column key="lowerLevelLimit" label="下级人数限制" prop="lowerLevelLimit" min-width="120" align="center" />
        <el-table-column key="rechargeAmount" label="充值金额限制" prop="rechargeAmount" min-width="120" align="center" />
        <el-table-column key="lowerLevelRechargeAmount" label="下级充值金额限制" prop="lowerLevelRechargeAmount" min-width="150" align="center" />
        <el-table-column key="purchase_price" label="采购价" prop="purchase_price" min-width="100" align="center" />
        <el-table-column key="selling_price" label="销售价" prop="selling_price" min-width="100" align="center" />
        <el-table-column key="createTime" label="创建时间" prop="createTime" min-width="160" align="center" />
        <el-table-column key="updateTime" label="更新时间" prop="updateTime" min-width="160" align="center" />
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button
              v-hasPerm="['genealogy:member-level:edit']"
              type="primary"
              size="small"
              link
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-hasPerm="['genealogy:member-level:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery()"
      />
    </el-card>

    <el-dialog v-model="editDialogVisible" title="编辑会员等级" width="500px">
      <el-form :model="editForm" label-width="180px">
        <el-form-item label="等级名称">
          <el-input v-model="editForm.levelName" placeholder="请输入等级名称" />
        </el-form-item>
        <el-form-item label="关联角色">
          <el-select v-model="editForm.roleId" placeholder="请选择角色">
            <el-option
              v-for="role in roleList"
              :key="role.code"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="等级">
          <el-input-number v-model="editForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="子等级">
          <el-input-number v-model="editForm.sort1" :min="0" :max="999" />
        </el-form-item>
        <!-- <el-form-item label="人数限制">
          <el-input-number v-model="editForm.personLimit" :min="0" />
        </el-form-item>
        <el-form-item label="下级人数限制">
          <el-input-number v-model="editForm.lowerLevelLimit" :min="0" />
        </el-form-item> -->
        <!-- <el-form-item label="充值金额限制">
          <el-input-number v-model="editForm.rechargeAmount" :min="0" :precision="2" :step="0.01" />
        </el-form-item>
        <el-form-item label="下级充值金额限制">
          <el-input-number v-model="editForm.lowerLevelRechargeAmount" :min="0" :precision="2" :step="0.01" />
        </el-form-item> -->
        <!-- <el-form-item label="采购价">
          <el-input-number v-model="editForm.purchase_price" :min="0" :precision="2" :step="0.01" />
        </el-form-item>
        <el-form-item label="销售价">
          <el-input-number v-model="editForm.selling_price" :min="0" :precision="2" :step="0.01" />
        </el-form-item> -->
        <el-form-item label="一级分销佣金比例（%）">
          <el-input-number v-model="editForm.proportionOne" :min="0" :max="100" :precision="2" :step="1" />
        </el-form-item>
        <el-form-item label="二级分销佣金比例（%）">
          <el-input-number v-model="editForm.proportionTwo" :min="0" :max="100" :precision="2" :step="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="deleteDialogVisible" title="删除确认" width="300px">
      <span>确定要删除该会员等级吗？</span>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="submitDelete">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import MemberLevelAPI from "@/api/genealogy/member-level.api";
import RoleAPI from "@/api/system/role.api";
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Search, Refresh, Plus } from '@element-plus/icons-vue';

const queryFormRef = ref();
const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);
const roleList = ref([]);
const selectedRoleId = ref('');
const filteredPageData = ref([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  memberLevelName: '',
});

const pageData = ref([]);

const editDialogVisible = ref(false);
const editForm = reactive({
  id: undefined,
  levelName: '',
  roleId: '',
  sort: 0,
  sort1: 0,
  // personLimit: 0,
  lowerLevelLimit: 0,
  rechargeAmount: 0,
  lowerLevelRechargeAmount: 0,
  purchase_price: 0,
  selling_price: 0,
  proportionOne: 0,
  proportionTwo: 0
});

const deleteDialogVisible = ref(false);
const currentDeleteId = ref<number>();

function handleQuery() {
  loading.value = true;
  MemberLevelAPI.getPage(queryParams)
    .then((data: any) => {
      pageData.value = data.list;
      total.value = data.total;
      handleRoleFilter();
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleRoleFilter() {
  if (!selectedRoleId.value) {
    filteredPageData.value = pageData.value;
  } else {
    filteredPageData.value = pageData.value.filter(item => item.roleId === selectedRoleId.value);
  }
}

// 查询角色
function handleRoleQuery() {
  loading.value = true;
  const RoleParams = {
    pageNum: 1,
    pageSize: 100,
    keywords: 'FAMILY'
  }
  RoleAPI.getPage(RoleParams)
    .then((data) => {
      roleList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleResetQuery() {
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

function handleEdit(row: any) {
  Object.assign(editForm, row);
  editDialogVisible.value = true;
}

function handleAdd() {
  Object.assign(editForm, {
    id: undefined,
    levelName: '',
    roleId: '',
    sort: 0,
    sort1: 0,
    // personLimit: 0,
    lowerLevelLimit: 0,
    rechargeAmount: 0,
    lowerLevelRechargeAmount: 0,
    purchase_price: 0,
    selling_price: 0
  });
  editDialogVisible.value = true;
}

function handleDelete(row: any) {
  currentDeleteId.value = row.id;
  deleteDialogVisible.value = true;
}

function submitEdit() {
  const api = editForm.id ? 
    MemberLevelAPI.edit(editForm.id, editForm) : 
    MemberLevelAPI.add(editForm);
    
  api.then(() => {
    ElMessage.success(editForm.id ? '编辑成功' : '新增成功');
    editDialogVisible.value = false;
    handleQuery();
  })
  .catch(() => {
    ElMessage.error(editForm.id ? '编辑失败' : '新增失败');
  })
  .finally(() => {
    loading.value = false;
  });
}

function submitDelete() {
  if (!currentDeleteId.value) return;
  
  loading.value = true;
  MemberLevelAPI.delete(currentDeleteId.value)
    .then(() => {
      ElMessage.success('删除成功');
      deleteDialogVisible.value = false;
      handleQuery();
    })
    .catch(() => {
      ElMessage.error('删除失败');
    })
    .finally(() => {
      loading.value = false;
    });
}

onMounted(() => {
  handleQuery();
  handleRoleQuery();
});
</script> 